
import jwt,datetime
from django.conf import settings

from jwt.exceptions import ExpiredSignatureError,DecodeError
from rest_framework import viewsets
from rest_framework.response import Response


# 生成token
def now_token(payload):
    token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
    return token

# 生成登录token
def login_token(payload):
    """设置有效期、第一次默认生成2个小时"""
    exp = datetime.datetime.now() + datetime.timedelta(hours=2)
    # exp = datetime.datetime.now().timestamp() + 10
    payload["exp"] = exp
    token = now_token(payload)

    # 刷新生成token，有效期15天
    exp = datetime.datetime.now() + datetime.timedelta(days=15)
    payload["exp"] = exp
    refresh_token = now_token(payload)
    return token,refresh_token


# 验证token
def check_token(token):
    try:
        payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=['HS256'])
        return payload
    except ExpiredSignatureError:
        # print("token过期")
        return Response({"code": 409, "msg": "token过期"})
    except DecodeError:
        # raise AuthenticationFailed("token认证失败")
        return Response({"code": 408, "msg": "请重新登录"})



